<template>
  <div v-if="state.versionCount > 0">
    {{ $t("371") + ": " + state.versionCount }}
    <a-button type="link" @click="goRecordVersion">{{ $t("372") }}</a-button>
  </div>
  <a-form layout="vertical">
    <a-form-item
      v-for="fd in lstFieldDefine"
      :key="fd.id"
      :label="fd.label"
      :required="fd.required"
      :disabled="state.roFields.findIndex((x) => x == fd.id) > -1"
    >
      <template #help>
        <span v-if="fd.inputHint">{{ fd.inputHint }}</span>
        <span v-if="fd.fieldType.C && fd.fieldType.C.unitLabel">{{
          $t("335") + ":" + fd.fieldType.C.unitLabel
        }}</span>
      </template>
      <multi-field-editor
        v-if="fd.multi"
        ref="refMfe"
        :field="fd"
        :codeSourceMap="codeSourceMap"
        :record="state.record"
        style="width: 95%"
      ></multi-field-editor>
      <div v-else>
        <a-input-number
          v-if="fd.fieldType.T == 'FtInt' || fd.fieldType.T == 'FtFloat'"
          v-model:value="fd.value"
          :disabled="state.roFields.findIndex((x) => x == fd.id) > -1"
          style="width: 95%"
        />
        <a-switch
          v-else-if="fd.fieldType.T == 'FtBool'"
          v-model:checked="fd.value"
          :disabled="state.roFields.findIndex((x) => x == fd.id) > -1"
        ></a-switch>
        <a-date-picker
          v-else-if="fd.fieldType.T == 'FtDate'"
          v-model:value="fd.value"
          valueFormat="YYYY-MM-DD"
          :locale="locale"
          :disabled="state.roFields.findIndex((x) => x == fd.id) > -1"
        ></a-date-picker>
        <a-time-picker
          v-else-if="fd.fieldType.T == 'FtTime'"
          v-model:value="fd.value"
          valueFormat="HH:mm:ss"
        ></a-time-picker>
        <a-date-picker
          v-else-if="fd.fieldType.T == 'FtDateTime'"
          v-model:value="fd.value"
          valueFormat="YYYY-MM-DD HH:mm:ss"
          showTime
          showNow
          :locale="locale"
        ></a-date-picker>
        <FileUploader v-else-if="fd.fieldType.T == 'FtFile'" :field="fd">
        </FileUploader>
        <a-select
          v-else-if="fd.fieldType.T == 'FtCode'"
          v-model:value="fd.value"
          :options="codeSourceMap[fd.id]"
          :field-names="{ label: 'l', value: 'c' }"
          style="width: 95%"
        >
        </a-select>
        <a-input-search
          v-else-if="
            fd.fieldType.T == 'FtModel' || fd.fieldType.T == 'FtModelSelf'
          "
          v-model:value="fd.display"
          :placeholder="$t('373')"
          @search="beginSelectRecord(fd)"
          style="width: 95%"
        ></a-input-search>
        <a-select
          v-else-if="fd.fieldType.T == 'FtUserId'"
          v-model:value="fd.value"
          :placeholder="$t('128')"
          style="width: 95%"
        >
          <a-select-option :value="uid">{{ $t("236") }}</a-select-option>
          <a-select-option
            v-for="item in appStore.otherUsers"
            :key="item.id"
            :value="item.id"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
        <div v-else-if="fd.fieldType.T == 'FtJson'">
          <JsonEditor v-model="fd.value" :canEdit="true"></JsonEditor>
        </div>
        <div v-else-if="fd.fieldType.T == 'FtYaml'">
          <YamlEditor v-model="fd.value" :canEdit="true"></YamlEditor>
        </div>
        <a-textarea
          v-else-if="
            fd.fieldType.T != 'FtComputed' &&
            fd.fieldType.T != 'FtAutoIncreaseInt' &&
            fd.fieldType.T != 'FtAutoIncreaseIntGlobal' &&
            fd.fieldType.T != 'FtUserSelf'
          "
          v-model:value="fd.value"
          auto-size
          :showCount="true"
          style="width: 95%"
        />
        <label v-else>自动计算，无需填报</label>
      </div>
    </a-form-item>
    <a-flex align="center" gap="small" style="margin-top: 8px">
      <a-checkbox
        v-if="!props.shareMode && channel.recordInEditting"
        v-model:checked="state.saveOldVersion"
        >{{ $t("374") }}</a-checkbox
      >
      <a-button type="primary" @click="doSaveRecord">{{ $t("224") }}</a-button>
    </a-flex>
  </a-form>
  <a-modal
    v-model:open="state.popRecordSelector"
    :title="$t('373')"
    width="1024px"
    :footer="null"
  >
    <RecordSelector
      ref="refRS"
      :field="state.curFd"
      @change="onSelectRecordChange"
    ></RecordSelector>
  </a-modal>
</template>
<script setup>
import { nextTick, onBeforeMount, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import CommonDefine from "@/component/CommonDefine";
import { computed } from "@vue/reactivity";
import "dayjs/locale/zh-cn";
import locale from "ant-design-vue/es/date-picker/locale/zh_CN";
import FileUploader from "@/component/field/FileUploader.vue";
import MultiFieldEditor from "@/component/field/MultiFieldEditor.vue";
import RecordSelector from "@/component/record/RecordSelector.vue";
import JsonEditor from "@/component/field/JsonEditor.vue";
import YamlEditor from "@/component/field/YamlEditor.vue";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const appStore = CommonDefine.appStore();
const channel = CommonDefine.channel();
const emits = defineEmits(["ok"]);
const state = reactive({
  saveOldVersion: false,
  versionCount: 0,
  popRecordSelector: false,
  curFd: undefined,
  enableVersion: false, // 是否启用版本管理功能
  roFields: [], // 不可修改的字段id列表
});
const router = useRouter();
const refRS = ref();
const lstFieldDefine = reactive([]);
const props = defineProps({ shareMode: { type: Boolean, default: false } });
const refMfe = ref([]);
const uid = computed(() => Number(localStorage.getItem("uid")));

const doSaveRecord = () => {
  let pd = { modelId: channel.selectedModel.id, fields: [] };
  lstFieldDefine.forEach((x) => {
    let fieldValue = {
      fieldId: x.id,
      value: x.value,
    };
    if (x.fieldType.T == "FtFile") {
      if (CommonDefine.useful(channel.uploadData)) {
        channel.uploadData.forEach((y) => {
          if (y.fid == x.id) {
            if (!CommonDefine.useful(fieldValue.value)) {
              fieldValue.value = {};
            }
            fieldValue.value.v = y.v;
            fieldValue.value.d = y.d;
          }
        });
      }
    }
    // 多值字段赋值
    if (x.multi) {
      refMfe.value.forEach((componentRef) => {
        let fv = componentRef.getValue();
        if (fv && fv.fid == x.id) {
          fieldValue.value = fv.value;
        }
      });
    }
    pd.fields.push(fieldValue);
  });
  if (CommonDefine.useful(channel.recordInEditting)) {
    pd.oldKey = channel.recordInEditting.meta.id;
    pd.oldToVersion = state.saveOldVersion;
  }
  let url = props.shareMode
    ? `/api/v1/record/share-save`
    : `/api/v1/record/save`;
  CommonDefine.apiPostArm(url, pd, (d) => {
    CommonDefine.alert(t("375"));
    // 清理界面
    lstFieldDefine.forEach((item) => {
      delete item["value"];
      delete item["display"];
    });
    refMfe.value.forEach((componentRef) => {
      componentRef.resetValue();
    });
    // 如果是修改记录，需要主动关闭界面，否则继续输入还是修改记录，易引起误操作
    if (CommonDefine.useful(pd.oldKey)) {
      emits("ok");
    }
  });
};

const beginSelectRecord = (fd) => {
  state.curFd = fd;
  state.popRecordSelector = true;
  // console.log(fd);
  // 选择本模型的记录的场景支持
  if (fd.fieldType.T == "FtModelSelf") {
    fd.fieldType.C = {
      displayField: fd.fieldType.C,
      provider: channel.selectedModel.id,
    };
  }
  nextTick(() => {
    refRS.value.loadFields();
  });
};

// 所有801类型字段的码表
const codeSourceMap = computed(() => {
  var r = {};
  lstFieldDefine.forEach((fd) => {
    if (fd.fieldType.T == "FtCode") {
      r[fd.id] = JSON.parse(fd.fieldType.C);
    }
  });
  return r;
});

const setRecord = () => {
  state.enableVersion = false;
  state.roFields = [];
  let recdd = channel.recordInEditting;
  if (recdd && recdd != null) {
    lstFieldDefine.forEach((field) => {
      if (recdd.value && recdd.value[field.id]) {
        field.value = recdd.value[field.id].C;
      }
    });
    // 判断是否启用版本管理功能
    state.enableVersion = recdd.meta.uid == localStorage.getItem("uid");
    if (state.enableVersion) {
      loadVersionCount();
    }
    // 判断disable哪些字段的编辑功能
    if (props.shareMode) {
      channel.visitToken.vg.ruleF.forEach((x) => {
        if (x.T == "SrfRo") {
          x.C.forEach((y) => state.roFields.push(y));
        }
      });
    }
    //
    nextTick(() => {
      refMfe.value.forEach((x) => {
        x.setValue();
      });
    });
  }
};

const loadVersionCount = () => {
  let recdd = channel.recordInEditting;
  CommonDefine.apiGetArm(
    `/api/v1/record/version-count/${recdd.meta.id}`,
    (d) => {
      state.versionCount = d;
    }
  );
};

const goRecordVersion = () => {
  router.push("/index/record-version");
};

// 连接字段记录修改回调
const onSelectRecordChange = (event) => {
  // console.log(event);
  lstFieldDefine.forEach((fd) => {
    if (fd.id == event.fid) {
      fd.display = event.rec.display;
      fd.value = event.rec.value;
    } else {
      return;
    }
  });
};

onBeforeMount(() => {
  CommonDefine.runWithFieldCache(channel.selectedModel.id, (fields) => {
    CommonDefine.clearArray(lstFieldDefine);
    fields.forEach((field) => {
      if (props.shareMode) {
        // 共享模式需要匹配访问规则，限制字段填报
      }
      lstFieldDefine.push(field);
    });
  });
  setRecord();
});

defineExpose({ setRecord });
</script>
